package cc.liyinghao.handler;

import cc.liyinghao.common.api.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获未处理异常，兜底异常
     */
    @ExceptionHandler(value = Exception.class)
    public Object handleException(Exception e, HttpServletRequest request) {
        log.error("未处理异常 -> {}", e.getClass());
        log.error("url -> {}", request.getRequestURL());
        log.error("msg -> {}", e.getMessage());
        log.error("stack trace -> {}", e.getStackTrace());
        return Result.error(e.getMessage());
    }

    /**
     * 参数异常处理，400参数校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object validationException(MethodArgumentNotValidException e, HttpServletRequest request) {
        log.info("参数异常 -> {}", e.getClass());
        log.info("url -> {}", request.getRequestURL());
        log.info("msg -> {}", e.getBindingResult().getFieldError().getDefaultMessage());
        log.info("stack trace -> {}", e.getStackTrace());
        return Result.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }

}
